package org.jboss.seam.wiki.core.dao;

import java.util.List;

import org.jboss.seam.wiki.core.preferences.WikiPreferenceValue;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.xelnaga.defiler.dao.hibernate.HibernateGenericDao;

@Repository
public class WikiPreferenceDaoImpl extends HibernateGenericDao<WikiPreferenceValue, Long> 
	implements WikiPreferenceDao{

	public WikiPreferenceDaoImpl() {
		super(WikiPreferenceValue.class);
	}

	@Transactional
	public void deleteByUser(Long userId) {
		String eql = "delete from WikiPreferenceValue wp where wp.user.userId = :user";
		getEntityManager().createQuery(eql).setParameter("user", userId).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<WikiPreferenceValue> getSystemValues(String entityName) {
		String eql = "select wp from WikiPreferenceValue wp" +
	      " where wp.entityName = :name and wp.user is null";
		return getEntityManager().createQuery(eql)
								 .setParameter("name", entityName)
								 .setHint("org.hibernate.cacheable", true)
								 .getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<WikiPreferenceValue> getUserValues(String entityName, Long userId) {
		String eql = "select wp from WikiPreferenceValue wp" +
		  " where wp.entityName = :name and wp.user.userId = :user";
		return getEntityManager().createQuery(eql)
								 .setParameter("name", entityName)
								 .setParameter("user", userId)
								 .setHint("org.hibernate.cacheable", true)
								 .getResultList();
	}

}
